﻿#region DaTestCatalog
/*----------------------------------------------------------------
// 文件名：DaTestCatalog.cs
// 功能描述：类TestCatalog的数据访问层
//
// 
// 创建时间：2009-04-14 DtataAccess template . Ver 4.0.20090408
//
// 修改标识： 
// 修改描述： 
//----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Globalization;
using System.Text;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

using EQT.Model;


namespace EQT.Dal
{
    ///可以继承更上层接口,ITestCatalog ,数据访问层基类DaBase，
    ///DaBase中包含了DbException异常处理静态方法
    public partial class DaTestCatalog : DaBase
    {
        #region SQL const
        internal const string TABLE_COLUMNS = " TEST_CTG_ID ,PARENT_CTG_ID ,TEST_CTG_NAME ,REM ,CREATE_TIME ,UPDATE_TIME ,TC_FLAG   ";

        internal const string SQL_INSERT = "INSERT INTO TEST_CATALOG (" + TABLE_COLUMNS + ") VALUES (@TestCtgId,@ParentCtgId,@TestCtgName,@Rem,@CreateTime,@UpdateTime,@TcFlag)";
        internal const string SQL_SELECT = "SELECT " + TABLE_COLUMNS + " FROM TEST_CATALOG  ";
        internal const string SQL_SELECT_ONE = SQL_SELECT + " WHERE TEST_CTG_ID=@TestCtgId";

        internal const string SQL_EXIST = "SELECT COUNT(*) FROM TEST_CATALOG  WHERE TEST_CTG_ID=@TestCtgId  ";
        internal const string SQL_UPDATE = "UPDATE TEST_CATALOG SET PARENT_CTG_ID=@ParentCtgId, TEST_CTG_NAME=@TestCtgName, REM=@Rem, CREATE_TIME=@CreateTime, UPDATE_TIME=@UpdateTime, TC_FLAG=@TcFlag WHERE TEST_CTG_ID=@TestCtgId";
        internal const string SQL_DELETE = "DELETE FROM TEST_CATALOG WHERE TEST_CTG_ID=@TestCtgId";
        internal const string SQL_COUNT = "SELECT COUNT(*) FROM Test_Catalog";
        #endregion

        private Database db;

        #region Constructor

        /// <summary>
        /// 默认构造函数，使用配置文件中默认的数据库配置。
        /// </summary>
        public DaTestCatalog()
        {
            this.db = DatabaseFactory.CreateDatabase();
        }
        /// <summary>
        /// 使用指定的databaseName数据库配置。
        /// </summary>
        /// <param name="databaseName">配置文件中数据库的配置名称。</param>
        public DaTestCatalog(string databaseName)
        {
            this.db = DatabaseFactory.CreateDatabase(databaseName);
        }

        public DaTestCatalog(Database db)
        {
            this.db = db;
        }

        #endregion

        //以下是CRUD方法，每个方法都有引入外部事务的版本



        #region static helper for Add
        ///build the command object.It never throw exception.
        internal static DbCommand ConstructAddCommand(Database db)
        {
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_INSERT);

            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString);
            db.AddInParameter(dbCommand, "ParentCtgId", DbType.AnsiString);
            db.AddInParameter(dbCommand, "TestCtgName", DbType.String);
            db.AddInParameter(dbCommand, "Rem", DbType.String);
            db.AddInParameter(dbCommand, "CreateTime", DbType.DateTime);
            db.AddInParameter(dbCommand, "UpdateTime", DbType.DateTime);
            db.AddInParameter(dbCommand, "TcFlag", DbType.AnsiStringFixedLength);
            return dbCommand;
        }
        internal static DbCommand ConstructAddCommand(Database db, MoTestCatalog entity)
        {
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_INSERT);
            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, entity.TestCtgId);
            db.AddInParameter(dbCommand, "ParentCtgId", DbType.AnsiString, entity.ParentCtgId);
            db.AddInParameter(dbCommand, "TestCtgName", DbType.String, entity.TestCtgName);
            db.AddInParameter(dbCommand, "Rem", DbType.String, entity.Rem);
            db.AddInParameter(dbCommand, "CreateTime", DbType.DateTime, entity.CreateTime);
            db.AddInParameter(dbCommand, "UpdateTime", DbType.DateTime, entity.UpdateTime);
            db.AddInParameter(dbCommand, "TcFlag", DbType.AnsiStringFixedLength, entity.TcFlag);
            return dbCommand;
        }

        internal static DbCommand PopulateAddCommandParameters(Database db, DbCommand addCmd, MoTestCatalog entity)
        {
            db.SetParameterValue(addCmd, "TestCtgId", entity.TestCtgId);
            db.SetParameterValue(addCmd, "ParentCtgId", entity.ParentCtgId);
            db.SetParameterValue(addCmd, "TestCtgName", entity.TestCtgName);
            db.SetParameterValue(addCmd, "Rem", entity.Rem);
            db.SetParameterValue(addCmd, "CreateTime", entity.CreateTime);
            db.SetParameterValue(addCmd, "UpdateTime", entity.UpdateTime);
            db.SetParameterValue(addCmd, "TcFlag", entity.TcFlag);
            return addCmd;
        }

        internal static DbCommand PopulateAddCommandParameters(Database db, DbCommand addCmd, DataRow row)
        {
            db.SetParameterValue(addCmd, "TestCtgId", row["TestCtgId"]);
            db.SetParameterValue(addCmd, "ParentCtgId", row["ParentCtgId"]);
            db.SetParameterValue(addCmd, "TestCtgName", row["TestCtgName"]);
            db.SetParameterValue(addCmd, "Rem", row["Rem"]);
            db.SetParameterValue(addCmd, "CreateTime", row["CreateTime"]);
            db.SetParameterValue(addCmd, "UpdateTime", row["UpdateTime"]);
            db.SetParameterValue(addCmd, "TcFlag", row["TcFlag"]);
            return addCmd;
        }

        #endregion

        #region Add
        /// <summary>
        ///在某事务下增加一条记录，事务没有commit
        /// </summary>
        public int Add(MoTestCatalog entity, DbTransaction trans)
        {
            if (entity == null) throw new ArgumentNullException("entity", "Could not add null MoTestCatalog.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");
            DbCommand dbCommand = ConstructAddCommand(db, entity);
            try
            {
                return db.ExecuteNonQuery(dbCommand, trans);
            }
            catch (DbException ex)
            {
                HandleDbException(ex, entity);
            }
            return 0;

        }
        public int Add(MoTestCatalog entity)
        {
            if (entity == null) throw new ArgumentNullException("entity", "Could not add null MoTestCatalog.");
            DbCommand dbCommand = ConstructAddCommand(db, entity);
            try
            {
                return db.ExecuteNonQuery(dbCommand);
            }
            catch (DbException ex)
            {
                HandleDbException(ex, entity);
            }
            return 0;
        }

        public int Add(ReadOnlyCollection<MoTestCatalog> entity, DbTransaction trans)
        {
            if (entity == null) throw new ArgumentNullException("entity", "ReadOnlyCollection<MoTestCatalog> Could not be null.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");
            int rc = 0;
            DbCommand dbCommand = ConstructAddCommand(db);
            int j = 0;
            try
            {
                for (j = 0; j < entity.Count; j++)
                {
                    PopulateAddCommandParameters(db, dbCommand, entity[j]);
                    rc += db.ExecuteNonQuery(dbCommand, trans);
                }
            }
            catch (DbException ex)
            {
                HandleDbException(ex, entity[j]);
                rc = 0;
            }
            return rc;
        }
        public int Add(ReadOnlyCollection<MoTestCatalog> entity)
        {
            if (entity == null) throw new ArgumentNullException("entity", "ReadOnlyCollection<MoTestCatalog> Could not be null.");

            int rc = 0;
            using (DbConnection cnn = db.CreateConnection())
            {
                DbTransaction trans = null;
                try
                {
                    cnn.Open();
                    using (trans = cnn.BeginTransaction())
                    {
                        rc = Add(entity, trans);//This function throw customer exception.
                        trans.Commit();
                    }
                    cnn.Close();
                }
                catch (DbException ex)
                {
                    if (trans != null) trans.Rollback();
                    HandleDbException(ex);
                    rc = 0;
                }

            }
            return rc;
        }

        public int Add(DataTable dt, DbTransaction trans)
        {
            if (dt == null) throw new ArgumentNullException("dt", "DataTable Could not be null.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            int rc = 0;
            DbCommand dbCommand = ConstructAddCommand(db);
            int j = 0;
            try
            {
                for (j = 0; j < dt.Rows.Count; j++)
                {
                    PopulateAddCommandParameters(db, dbCommand, dt.Rows[j]);
                    rc += db.ExecuteNonQuery(dbCommand, trans);
                }
            }
            catch (DbException ex)
            {
                HandleDbException(ex, dt.Rows[j]);
            }

            return rc;
        }
        public int Add(DataTable dt)
        {
            if (dt == null) throw new ArgumentNullException("dt", "DataTable Could not be null.");

            int rc = 0;
            using (DbConnection cnn = db.CreateConnection())
            {
                DbTransaction trans = null;
                try
                {
                    cnn.Open();
                    using (trans = cnn.BeginTransaction())
                    {
                        rc = Add(dt, trans);
                        trans.Commit();
                        cnn.Close();
                    }
                }
                catch (DbException ex)
                {
                    if (trans != null) trans.Rollback();
                    HandleDbException(ex);
                    rc = 0;
                }

            }
            return rc;
        }
        #endregion

        #region Update
        #region helper
        internal static DbCommand ConstructUpdateCommand(Database db)
        {
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_UPDATE);
            db.AddInParameter(dbCommand, "ParentCtgId", DbType.AnsiString);
            db.AddInParameter(dbCommand, "TestCtgName", DbType.String);
            db.AddInParameter(dbCommand, "Rem", DbType.String);
            db.AddInParameter(dbCommand, "CreateTime", DbType.DateTime);
            db.AddInParameter(dbCommand, "UpdateTime", DbType.DateTime);
            db.AddInParameter(dbCommand, "TcFlag", DbType.AnsiStringFixedLength);
            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString);

            return dbCommand;
        }
        internal static DbCommand ConstructUpdateCommand(Database db, MoTestCatalog entity)
        {
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_UPDATE);
            db.AddInParameter(dbCommand, "ParentCtgId", DbType.AnsiString, entity.ParentCtgId);
            db.AddInParameter(dbCommand, "TestCtgName", DbType.String, entity.TestCtgName);
            db.AddInParameter(dbCommand, "Rem", DbType.String, entity.Rem);
            db.AddInParameter(dbCommand, "CreateTime", DbType.DateTime, entity.CreateTime);
            db.AddInParameter(dbCommand, "UpdateTime", DbType.DateTime, entity.UpdateTime);
            db.AddInParameter(dbCommand, "TcFlag", DbType.AnsiStringFixedLength, entity.TcFlag);
            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, entity.TestCtgId);

            return dbCommand;
        }

        internal static DbCommand PopulateUpdateCommandParameters(Database db, DbCommand updateCmd, MoTestCatalog entity)
        {
            db.SetParameterValue(updateCmd, "ParentCtgId", entity.ParentCtgId);
            db.SetParameterValue(updateCmd, "TestCtgName", entity.TestCtgName);
            db.SetParameterValue(updateCmd, "Rem", entity.Rem);
            db.SetParameterValue(updateCmd, "CreateTime", entity.CreateTime);
            db.SetParameterValue(updateCmd, "UpdateTime", entity.UpdateTime);
            db.SetParameterValue(updateCmd, "TcFlag", entity.TcFlag);
            db.SetParameterValue(updateCmd, "TestCtgId", entity.TestCtgId);
            return updateCmd;
        }
        internal static DbCommand PopulateUpdateCommandParameters(Database db, DbCommand updateCmd, DataRow row)
        {
            db.SetParameterValue(updateCmd, "ParentCtgId", row["ParentCtgId"]);
            db.SetParameterValue(updateCmd, "TestCtgName", row["TestCtgName"]);
            db.SetParameterValue(updateCmd, "Rem", row["Rem"]);
            db.SetParameterValue(updateCmd, "CreateTime", row["CreateTime"]);
            db.SetParameterValue(updateCmd, "UpdateTime", row["UpdateTime"]);
            db.SetParameterValue(updateCmd, "TcFlag", row["TcFlag"]);
            db.SetParameterValue(updateCmd, "TestCtgId", row["TestCtgId"]);
            return updateCmd;
        }
        #endregion
        /// <summary>
        /// 根据主键更新实体。注意:主键列本身并未更新。
        /// </summary>	
        public int Update(MoTestCatalog entity, DbTransaction trans)
        {
            if (entity == null) throw new ArgumentNullException("entity", "MoTestCatalog Could not be null.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");
            DbCommand dbCommand = ConstructUpdateCommand(db, entity);
            try
            {
                return db.ExecuteNonQuery(dbCommand, trans);
            }
            catch (DbException ex)
            {
                HandleDbException(ex, entity);
            }
            return 0;
        }
        public int Update(MoTestCatalog entity)
        {
            if (entity == null) throw new ArgumentNullException("entity", "MoTestCatalog Could not be null.");
            DbCommand dbCommand = ConstructUpdateCommand(db, entity);
            try
            {
                return db.ExecuteNonQuery(dbCommand);
            }
            catch (DbException ex)
            {
                HandleDbException(ex, entity);
            }
            return 0;
        }
        public int Update(ReadOnlyCollection<MoTestCatalog> entity, DbTransaction trans)
        {
            if (entity == null) throw new ArgumentNullException("entity", "ReadOnlyCollection<MoTestCatalog> Could not be null.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            int rc = 0; int j = 0;
            DbCommand dbCommand = ConstructUpdateCommand(db);
            try
            {
                for (j = 0; j < entity.Count; j++)
                {
                    PopulateUpdateCommandParameters(db, dbCommand, entity[j]);
                    rc += db.ExecuteNonQuery(dbCommand, trans);
                }
            }
            catch (DbException ex)
            {
                HandleDbException(ex, entity[j]);
                rc = 0;
            }
            return rc;
        }
        public int Update(ReadOnlyCollection<MoTestCatalog> entity)
        {
            if (entity == null) throw new ArgumentNullException("entity", "ReadOnlyCollection<MoTestCatalog> Could not be null.");

            int rc = 0;
            using (DbConnection cnn = db.CreateConnection())
            {
                DbTransaction trans = null;
                try
                {
                    cnn.Open();
                    using (trans = cnn.BeginTransaction())
                    {
                        rc = Update(entity, trans);
                        trans.Commit();
                    }
                    cnn.Close();
                }
                catch (DbException ex)
                {
                    if (trans != null) trans.Rollback();
                    HandleDbException(ex);
                }
            }
            return rc;
        }
        public int Update(DataTable dt, DbTransaction trans)
        {
            if (dt == null || dt.Rows.Count == 0) return 0;
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            int rc = 0; int j = 0;
            DbCommand dbCommand = ConstructUpdateCommand(db);
            try
            {
                for (j = 0; j < dt.Rows.Count; j++)
                {
                    PopulateUpdateCommandParameters(db, dbCommand, dt.Rows[j]);
                    rc += db.ExecuteNonQuery(dbCommand, trans);
                }
            }
            catch (DbException ex)
            {
                HandleDbException(ex, dt.Rows[j]);
                rc = 0;
            }
            return rc;

        }
        public int Update(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0) return 0;
            int rc = 0;
            using (DbConnection cnn = db.CreateConnection())
            {
                DbTransaction trans = null;
                try
                {
                    cnn.Open();
                    using (trans = cnn.BeginTransaction())
                    {
                        rc = Update(dt, trans);
                        trans.Commit();
                    }
                    cnn.Close();
                }
                catch (DbException ex)
                {
                    if (trans != null) trans.Rollback();
                    HandleDbException(ex);
                    rc = 0;
                }

            }
            return rc;
        }
        #endregion

        #region Update By DataSet
        internal static void PrepareDataAdapterCommand(Database db, out DbCommand dbInsertCommand,
                             out DbCommand dbUpdateCommand, out DbCommand dbDeleteCommand)
        {
            dbInsertCommand = db.GetSqlStringCommand(SQL_INSERT);
            #region set insert cmd parameters
            db.AddInParameter(dbInsertCommand, "TestCtgId", DbType.AnsiString, "TEST_CTG_ID", DataRowVersion.Current);
            db.AddInParameter(dbInsertCommand, "ParentCtgId", DbType.AnsiString, "PARENT_CTG_ID", DataRowVersion.Current);
            db.AddInParameter(dbInsertCommand, "TestCtgName", DbType.String, "TEST_CTG_NAME", DataRowVersion.Current);
            db.AddInParameter(dbInsertCommand, "Rem", DbType.String, "REM", DataRowVersion.Current);
            db.AddInParameter(dbInsertCommand, "CreateTime", DbType.DateTime, "CREATE_TIME", DataRowVersion.Current);
            db.AddInParameter(dbInsertCommand, "UpdateTime", DbType.DateTime, "UPDATE_TIME", DataRowVersion.Current);
            db.AddInParameter(dbInsertCommand, "TcFlag", DbType.AnsiStringFixedLength, "TC_FLAG", DataRowVersion.Current);
            #endregion
            dbUpdateCommand = db.GetSqlStringCommand(SQL_UPDATE);
            #region Set update cmd value parameters
            db.AddInParameter(dbUpdateCommand, "ParentCtgId", DbType.AnsiString, "PARENT_CTG_ID", DataRowVersion.Current);
            db.AddInParameter(dbUpdateCommand, "TestCtgName", DbType.String, "TEST_CTG_NAME", DataRowVersion.Current);
            db.AddInParameter(dbUpdateCommand, "Rem", DbType.String, "REM", DataRowVersion.Current);
            db.AddInParameter(dbUpdateCommand, "CreateTime", DbType.DateTime, "CREATE_TIME", DataRowVersion.Current);
            db.AddInParameter(dbUpdateCommand, "UpdateTime", DbType.DateTime, "UPDATE_TIME", DataRowVersion.Current);
            db.AddInParameter(dbUpdateCommand, "TcFlag", DbType.AnsiStringFixedLength, "TC_FLAG", DataRowVersion.Current);
            #endregion
            #region set update cmd pk where parameters
            db.AddInParameter(dbUpdateCommand, "TestCtgId", DbType.AnsiString, "TEST_CTG_ID", DataRowVersion.Current);
            #endregion
            dbDeleteCommand = db.GetSqlStringCommand(SQL_DELETE);
            #region set delete cmd pk where parameters
            db.AddInParameter(dbDeleteCommand, "TestCtgId", DbType.AnsiString, "TEST_CTG_ID", DataRowVersion.Current);
            #endregion
        }



        /// <summary>
        /// 通过DataSet修改表数据
        /// </summary>
        /// <param name="dst">DataSet ,contain the all data.</param>
        /// <param name="strTableName">The taget table .</param>
        /// <param name="trans">The DbTransaction,could not be null.</param>
        /// <returns>how many rows to be modifid.</returns>
        public int UpdateByDataSet(DataSet dst, string strTableName, DbTransaction trans)
        {
            if (dst == null) throw new ArgumentNullException("dst", "DataSet Could not be null.");
            if (String.IsNullOrEmpty(strTableName)) throw new ArgumentNullException("strTableName", "The taget table name should not be null or blank.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");
            DbCommand dbInsertCommand = null;
            DbCommand dbUpdateCommand = null;
            DbCommand dbDeleteCommand = null;
            PrepareDataAdapterCommand(db, out dbInsertCommand, out dbUpdateCommand, out dbDeleteCommand);
            try
            {
                return db.UpdateDataSet(dst, strTableName, dbInsertCommand, dbUpdateCommand, dbDeleteCommand, trans);
            }
            catch (DbException ex)
            {
                trans.Rollback();
                HandleDbException(ex);
            }
            return -1;//TODO:Should return Application Specific Error Code.
        }

        /// <summary>
        /// 通过DataSet修改表数据（不带事务）
        /// </summary>
        public int UpdateByDataSet(DataSet dst, string strTableName)
        {
            if (dst == null) throw new ArgumentNullException("dst", "DataSet Could not be null.");
            if (String.IsNullOrEmpty(strTableName)) throw new ArgumentNullException("strTableName", "The taget table name should not be null or blank.");

            DbCommand dbInsertCommand = null;
            DbCommand dbUpdateCommand = null;
            DbCommand dbDeleteCommand = null;
            PrepareDataAdapterCommand(db, out dbInsertCommand, out dbUpdateCommand, out dbDeleteCommand);
            try
            {
                return db.UpdateDataSet(dst, strTableName, dbInsertCommand, dbUpdateCommand, dbDeleteCommand, UpdateBehavior.Transactional);
            }
            catch (DbException ex)
            {
                HandleDbException(ex);
            }
            return 0;//TODO:Should return Application Specific Error Code.			
        }



        #endregion

        #region Delete
        #region helper
        internal static DbCommand ConstructDeleteCommand(Database db)
        {
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_DELETE);

            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString);

            return dbCommand;
        }
        internal static DbCommand ConstructDeleteCommand(Database db, MoTestCatalog entity)
        {
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_DELETE);

            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, entity.TestCtgId);

            return dbCommand;
        }
        #endregion helper
        /// <summary>
        /// delete by pk(entity)
        /// </summary>	
        public int Delete(MoTestCatalog entity, DbTransaction trans)
        {
            if (entity == null) throw new ArgumentNullException("entity", "MoTestCatalog Could not be null.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");
            DbCommand dbCommand = ConstructDeleteCommand(db, entity);
            try
            {
                return db.ExecuteNonQuery(dbCommand, trans);
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex, entity);
            }
            return 0;
        }
        public int Delete(MoTestCatalog entity)
        {
            if (entity == null) throw new ArgumentNullException("entity", "MoTestCatalog Could not be null.");
            DbCommand dbCommand = ConstructDeleteCommand(db, entity);
            try
            {
                return db.ExecuteNonQuery(dbCommand);
            }
            catch (DbException ex)
            {
                HandleDbException(ex, entity);
            }
            return 0;
        }
        /// <summary>
        /// mul-delete
        /// </summary>	
        public int Delete(ReadOnlyCollection<MoTestCatalog> entities, DbTransaction trans)
        {
            if (entities == null) throw new ArgumentNullException("entities", "ReadOnlyCollection<MoTestCatalog> Could not be null.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            int rc = 0;
            int j = 0;
            DbCommand dbCommand = ConstructDeleteCommand(db);
            try
            {
                for (j = 0; j < entities.Count; j++)
                {
                    db.SetParameterValue(dbCommand, "TestCtgId", entities[j].TestCtgId);
                    rc += db.ExecuteNonQuery(dbCommand, trans);
                }
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex, entities[j]);
                rc = 0;
            }
            return rc;
        }
        public int Delete(ReadOnlyCollection<MoTestCatalog> entities)
        {
            if (entities == null) throw new ArgumentNullException("entities", "ReadOnlyCollection<MoTestCatalog> Could not be null.");

            int rc = 0;
            using (DbConnection cnn = db.CreateConnection())
            {
                DbTransaction trans = null;
                try
                {
                    cnn.Open();
                    using (trans = cnn.BeginTransaction())
                    {
                        rc = Delete(entities, trans);
                        trans.Commit();
                    }
                    cnn.Close();
                }
                catch (DbException ex)
                {
                    if (trans != null) trans.Rollback();
                    HandleDbException(ex);
                }
            }
            return rc;
        }

        /// <summary>
        /// delete via DataTable
        /// </summary>	
        public int Delete(DataTable dt, DbTransaction trans)
        {
            if (dt == null || dt.Rows.Count == 0) return 0;
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            int rc = 0;
            int j = 0;
            DbCommand dbCommand = ConstructDeleteCommand(db);
            try
            {
                for (j = 0; j < dt.Rows.Count; j++)
                {
                    db.SetParameterValue(dbCommand, "TestCtgId", dt.Rows[j]["TEST_CTG_ID"]);
                    rc += db.ExecuteNonQuery(dbCommand, trans);
                }
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex, dt.Rows[j]);
                rc = 0;
            }
            return rc;

        }
        public int Delete(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0) return 0;
            int rc = 0;
            using (DbConnection cnn = db.CreateConnection())
            {
                DbTransaction trans = null;
                try
                {
                    cnn.Open();
                    using (trans = cnn.BeginTransaction())
                    {
                        rc = Delete(dt, trans);
                        trans.Commit();
                    }
                    cnn.Close();
                }
                catch (DbException ex)
                {
                    if (trans != null) trans.Rollback();
                    HandleDbException(ex);
                }

            }
            return rc;
        }

        /// <summary>
        /// delete via PK Filds.
        /// </summary>	
        public int DeleteByPK(string testCtgId, DbTransaction trans)
        {
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_DELETE);
            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, testCtgId);
            try
            {
                return db.ExecuteNonQuery(dbCommand, trans);
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex);
            }
            return 0;
        }
        public int DeleteByPK(string testCtgId)
        {
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_DELETE);
            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, testCtgId);
            try
            {
                return db.ExecuteNonQuery(dbCommand);
            }
            catch (DbException ex)
            {
                HandleDbException(ex);
            }
            return -1;
        }

        public int DeleteByWhereClause(string where)
        {
            try
            {
                return db.ExecuteNonQuery(CommandType.Text, "DELETE FROM TEST_CATALOG " + where);
            }
            catch (DbException ex)
            {
                HandleDbException(ex);
            }
            return -1;

        }

        public int DeleteByWhereClause(string where, DbTransaction trans)
        {
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");
            try
            {
                return db.ExecuteNonQuery(trans, CommandType.Text, "DELETE FROM TEST_CATALOG " + where);
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex);
            }
            return -1;

        }

        #endregion

        #region Query All by condition
        /// <summary>
        /// 返回满足WHERE条件的记录的集合,若condition为空，则查询所有
        /// </summary>		
        public DataSet Query(string condition)
        {
            try
            {
                return db.ExecuteDataSet(CommandType.Text, SQL_SELECT + condition);
            }
            catch (DbException ex)
            {
                HandleDbException(ex);
            }
            return null;
        }
        public DataSet Query(string condition, DbTransaction trans)
        {
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_SELECT + condition);
            try
            {
                return db.ExecuteDataSet(dbCommand, trans);
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex);
            }
            return null;
        }
        #endregion

        #region GetEntity(s)
        /// <summary>
        ///根据主键返回一个实体对象
        /// </summary>
        public MoTestCatalog GetEntity(string testCtgId)
        {
            MoTestCatalog entity = new MoTestCatalog();
            entity.TestCtgId = testCtgId;
            if (GetEntityEx(ref entity))
            {
                return entity;
            }
            else
            {
                return null;
            }
        }

        public MoTestCatalog GetEntity(string testCtgId, DbTransaction trans)
        {
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");
            MoTestCatalog entity = new MoTestCatalog();
            entity.TestCtgId = testCtgId;
            if (GetEntityEx(ref entity, trans))
            {
                return entity;
            }
            else
            {
                return null;
            }
        }
        #region internal help function
        internal static DbCommand ConstructSelectOneCommand(Database db, MoTestCatalog entity)
        {
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_SELECT_ONE);

            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, entity.TestCtgId);
            return dbCommand;
        }

        internal static void PopulateEntityByDataReader(IDataReader reader, ref MoTestCatalog entity)
        {
            if (!reader.IsDBNull(0)) entity.TestCtgId = reader.GetString(0);
            if (!reader.IsDBNull(1)) entity.ParentCtgId = reader.GetString(1);
            if (!reader.IsDBNull(2)) entity.TestCtgName = reader.GetString(2);
            if (!reader.IsDBNull(3)) entity.Rem = reader.GetString(3);
            if (!reader.IsDBNull(4)) entity.CreateTime = reader.GetDateTime(4);
            if (!reader.IsDBNull(5)) entity.UpdateTime = reader.GetDateTime(5);
            if (!reader.IsDBNull(6)) entity.TcFlag = reader.GetString(6);
        }
        #endregion
        /// <summary>
        ///实体的主键已经赋值。需要注意的是，实体应该中是一个类，而不是结构.
        ///如果实体是结构，为了避免复制对象，应考虑使用ref关键字。
        /// </summary>
        public bool GetEntityEx(ref MoTestCatalog entity)
        {
            if (entity == null) throw new ArgumentNullException("entity", "MoTestCatalog can not be null.");
            DbCommand dbCommand = ConstructSelectOneCommand(db, entity);
            try
            {
                using (IDataReader reader = db.ExecuteReader(dbCommand))
                {
                    if (reader.Read())
                    {
                        PopulateEntityByDataReader(reader, ref entity);
                        return true;
                    }
                }
            }
            catch (DbException ex)
            {
                HandleDbException(ex, entity);
            }
            return false;
        }
        public bool GetEntityEx(ref MoTestCatalog entity, DbTransaction trans)
        {
            if (entity == null) throw new ArgumentNullException("entity", "MoTestCatalog Could not be null.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            DbCommand dbCommand = ConstructSelectOneCommand(db, entity);
            try
            {
                using (IDataReader reader = db.ExecuteReader(dbCommand, trans))
                {
                    if (reader.Read())
                    {
                        PopulateEntityByDataReader(reader, ref entity);
                        return true;
                    }
                }
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex, entity);
            }
            return false;

        }

        public Collection<MoTestCatalog> GetEntities(string condition, DbTransaction trans)
        {
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            Collection<MoTestCatalog> list = new Collection<MoTestCatalog>();
            try
            {
                using (IDataReader reader = db.ExecuteReader(trans, CommandType.Text, String.IsNullOrEmpty(condition) ? SQL_SELECT : SQL_SELECT + condition))
                {
                    while (reader.Read())
                    {
                        MoTestCatalog entity = new MoTestCatalog();
                        PopulateEntityByDataReader(reader, ref entity);
                        list.Add(entity);
                    }
                }
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex);
            }
            return list;

        }


        public Collection<MoTestCatalog> GetEntities(string condition)
        {
            Collection<MoTestCatalog> list = new Collection<MoTestCatalog>();
            try
            {
                using (IDataReader reader = db.ExecuteReader(CommandType.Text, String.IsNullOrEmpty(condition) ? SQL_SELECT : SQL_SELECT + " " + condition))
                {
                    while (reader.Read())
                    {
                        MoTestCatalog entity = new MoTestCatalog();
                        PopulateEntityByDataReader(reader, ref entity);
                        list.Add(entity);
                    }
                }
            }
            catch (DbException ex)
            {
                HandleDbException(ex);
            }
            return list;
        }
        #endregion

        #region Count
        /// <summary>
        /// 返回表的记录总数
        /// </summary>
        public int GetCount()
        {
            return Convert.ToInt32(db.ExecuteScalar(CommandType.Text, SQL_COUNT), CultureInfo.InvariantCulture);
        }

        public int GetCount(DbTransaction trans)
        {
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            try
            {
                return Convert.ToInt32(db.ExecuteScalar(trans, CommandType.Text, SQL_COUNT), CultureInfo.InvariantCulture);
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex);
            }
            return -1;
        }

        /// <summary>
        /// 返回满足WHERE条件记录数
        /// </summary>
        public int GetCount(string where)
        {
            return Convert.ToInt32(db.ExecuteScalar(CommandType.Text, SQL_COUNT + where), CultureInfo.InvariantCulture);
        }

        public int GetCount(string where, DbTransaction trans)
        {
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            try
            {
                return Convert.ToInt32(db.ExecuteScalar(trans, CommandType.Text, SQL_COUNT + where), CultureInfo.InvariantCulture);
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                HandleDbException(ex);
            }
            return -1;
        }
        #endregion

        #region Check isExist
        /// <summary>
        /// 判断是否存在此主键的记录
        /// </summary>
        public bool IsExist(string testCtgId)
        {
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_EXIST);
            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, testCtgId);
            try
            {
                return Convert.ToInt32(db.ExecuteScalar(dbCommand), CultureInfo.InvariantCulture) > 0;
            }
            catch (DbException ex)
            {
                throw new DalException("Data Access Error:", ex);
            }
        }

        public bool IsExist(string testCtgId, DbTransaction trans)
        {
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            DbCommand dbCommand = db.GetSqlStringCommand(SQL_EXIST);
            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, testCtgId);
            try
            {
                return Convert.ToInt32(db.ExecuteScalar(dbCommand, trans), CultureInfo.InvariantCulture) > 0;
            }
            catch (DbException ex)
            {
                if (trans != null) trans.Rollback();
                throw new DalException("Data Access Error:", ex);
            }

        }

        public bool IsExist(MoTestCatalog entity, DbTransaction trans)
        {
            if (entity == null) throw new ArgumentNullException("entity", "MoTestCatalog can not be null.");
            if (trans == null) throw new ArgumentNullException("trans", "DbTransaction can not be null.");

            DbCommand dbCommand = db.GetSqlStringCommand(SQL_EXIST);
            #region set pk where parameters
            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, entity.TestCtgId);
            #endregion
            try
            {
                return Convert.ToInt32(db.ExecuteScalar(dbCommand, trans), CultureInfo.InvariantCulture) > 0;
            }
            catch (DbException ex)
            {
                throw new DalException("Data Access Error:", ex);
            }
        }

        public bool IsExist(MoTestCatalog entity)
        {
            if (entity == null) throw new ArgumentNullException("entity", "MoTestCatalog can not be null.");
            DbCommand dbCommand = db.GetSqlStringCommand(SQL_EXIST);
            #region set pk where parameters
            db.AddInParameter(dbCommand, "TestCtgId", DbType.AnsiString, entity.TestCtgId);
            #endregion
            try
            {
                return Convert.ToInt32(db.ExecuteScalar(dbCommand), CultureInfo.InvariantCulture) > 0;
            }
            catch (DbException ex)
            {
                throw new DalException("Data Access Error:", ex);
            }
        }
        #endregion


    }
}
#endregion

